package org.fastsyncer.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 * 
 * @ClassName: LoginInterceptor
 * @Description: 登录拦截器：验证用户操作访问权限
 * @author AE86
 * @date: 2017年7月6日 下午10:42:18
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Ticket ticket;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证session会话
        HttpSession session = request.getSession();
        if(ticket.validateTicket(session)){
            return true;
        }

        String loginUrl = ticket.getLoginUrl();
        logger.error("Validate ticket failed, redirect to {}", loginUrl);
        response.sendRedirect(loginUrl);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
